package pl.lodz.p.beans;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import pl.lodz.p.beans.utils.HibernateUtil;
import pl.lodz.p.beans.utils.Util;
import pl.lodz.p.model.User;
import pl.lodz.p.model.enums.AccountType;
import pl.lodz.p.services.UserService;
import pl.lodz.p.services.UserServiceImpl;

public class LoginBean implements Serializable {
 
    private static final long serialVersionUID = 1L;
    private String password;
    private String message, uname;
    private User loginUser;
    private User loginPersonel;
    private User registeredUser = new User();
    private UserService userService = new UserServiceImpl();
    private String registerResult;
    private String passwordCheck;
    private Boolean loginAsOther = new Boolean(false);
    private Boolean registration = false;
    
    public boolean isLogin() {
		return loginUser != null ? true : false;
	}

	public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getUname() {
        return uname;
    }
 
    public void setUname(String uname) {
        this.uname = uname;
    }
 
    public String loginProject() {
    	HibernateUtil util = new HibernateUtil();
    	util.init();
        boolean result = login(uname, password);
        if (result) {
            // get Http Session and store username
            HttpSession session = Util.getSession();
            session.setAttribute("username", uname);
            return loginUser.getAccType().equals(AccountType.PATIENT) ? 
            		"patientStart?faces-redirect=true" : 
            			"workerStart?faces-redirect=true";
        } else {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Invalid Login!",
                    "Please Try Again!"));
            return "login";
        }
    }
 
    public boolean login(String login, String password) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			User u = (User) session.createQuery("from User where login = ? and active = 1").setParameter(0, login).uniqueResult();
			if (u == null){
				return false;
			} else {
				loginUser = u;
			}
			if (u.getPassword().equals(password)){
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return false;
	}
    
    public String register(){
    	registration = true;
    	registeredUser.setAccType(AccountType.PATIENT);
    	return "";
    }
    
    public String toLogin(){
    	registration = false;
    	return "";
    }
    
    public String registerUser(){
    	if (registeredUser.getAccType().equals(AccountType.PATIENT)){
    		registeredUser.setActive(true);
    	}
    	registerResult = userService.newUser(registeredUser);
    	if (registerResult.equals("added")){
    		registeredUser = new User();
    		return "login";
    	} else {
    		FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Problem with " + registerResult));
    	}
    	toLogin();
    	return "/pages/login?faces-redirect=true";
    }
    
	public String logout() {
		HttpSession session = Util.getSession();
		session.invalidate();
		loginUser = null;
		return "/pages/login?faces-redirect=true";
	}

	public User getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(User loginUser) {
		this.loginUser = loginUser;
	}
	
	public User getRegisteredUser() {
		return registeredUser;
	}

	public void setRegisteredUser(User registeredUser) {
		this.registeredUser = registeredUser;
	}

	/**
	 * @return the passwordCheck
	 */
	public String getPasswordCheck() {
		return passwordCheck;
	}

	/**
	 * @param passwordCheck the passwordCheck to set
	 */
	public void setPasswordCheck(String passwordCheck) {
		this.passwordCheck = passwordCheck;
	}

	/**
	 * @return the loginPersonel
	 */
	public User getLoginPersonel() {
		return loginPersonel;
	}

	/**
	 * @param loginPersonel the loginPersonel to set
	 */
	public void setLoginPersonel(User loginPersonel) {
		this.loginPersonel = loginPersonel;
	}

	/**
	 * @return the loginAsOther
	 */
	public Boolean getLoginAsOther() {
		return loginAsOther;
	}

	/**
	 * @param loginAsOther the loginAsOther to set
	 */
	public void setLoginAsOther(Boolean loginAsOther) {
		this.loginAsOther = loginAsOther;
	}

	public String logoutAsUser(){
		setLoginUser(loginPersonel);//musi byc pierwsze
		setLoginPersonel(null);
		setLoginAsOther(new Boolean(false));
		return "";
	}
	
	public String logStats(){
		HibernateUtil hu = new HibernateUtil();
		for (String s : hu.getStats().getQueries()) {
			System.out.println(s);
		}
		return "";
	}

	public Boolean getRegistration() {
		return registration;
	}

	public void setRegistration(Boolean registration) {
		this.registration = registration;
	}
}